<template>
	<div>
		<ProTable ref="proTable" title="采购需求单" :columns="columns" :requestApi="getTableList" :init-param="initParam">
			<template #searchHeader>
				<div class="demnd-width-scroll">
					<div class="material" v-for="item in orderBuyList" :key="item.materialCode">
						<div>物料编码：{{ item.materialCode }}</div>
						<div>待采购数量：{{ item.amount }}</div>
						<div>年份：{{ item.year }}</div>
					</div>
				</div>
			</template>
			<!-- 表格 功能 按钮 -->
			<template #otherButton>
				<el-button @click="onExport" v-auth="'order:page:export:invoke'"> 导出 </el-button>
			</template>
			<!-- Expand -->
			<template #expand="scope">
				{{ scope.row }}
			</template>

			<!-- 表格操作 -->
			<template #operation="{ row }">
				<el-button type="primary" v-if="row?.pushStatus == 0" link v-auth="'order:push:invoke'" @click="onPush(row)"> 推送履约 </el-button>
				<el-divider direction="vertical" v-if="row?.pushStatus == 0" v-auth="'order:push:invoke'" />
				<el-button type="primary" link v-auth="'order:seller-remark:invoke'" @click="onRemark(row)"> 备注 </el-button>
				<el-divider direction="vertical" v-auth="'order:seller-remark:invoke'" />
				<el-button type="primary" link v-auth="'order:details:invoke'" @click="() => $router.push({ path: `/order/query/detail/${row.id}` })">
					查看详情
				</el-button>
			</template>
		</ProTable>
		<Remark :visible="remarkVisible" :row="remarkRow" @handleClose="closeRemark"></Remark>
	</div>
</template>

<script setup lang="tsx" name="fulfillDemand">
import { onMounted, ref, reactive, computed, nextTick } from 'vue';
import dayjs from 'dayjs';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import ProTable from '../../../../components/ProTable/index.vue';
import { ProTableInstance, ColumnProps } from '../../../../components/ProTable/interface';
import { fenToYuan } from '/@/utils/commonFunction';
import { fetchOrderBuy, fetchOrderList, fetchOrderExport, fetchOrderPush } from '/@/api/order';
import { useDownload } from '/@/hooks/useDownload';
import Remark from '/@/views/pages/order/query/dialog/remark.vue';
import constant from '/@/utils/constant';

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

const router = useRouter();
const orderBuyList = ref<any>([]);

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	paramCode: 'orderNo',
	paramTimeType: 'create',
	pushStatus: 0,
	// orderStatus: 1,
	orderType: '',
});

const handleParams = (params: any) => {
	let data = {
		...params,
	};
	if (data.paramValue) {
		data[data.paramCode] = data.paramValue;
		delete data.paramValue;
		delete data.paramCode;
	}
	if (data.paramTime) {
		data[`${data.paramTimeType}StartTime`] = dayjs(data.paramTime[0]).format('YYYY-MM-DD');
		data[`${data.paramTimeType}EndTime`] = dayjs(data.paramTime[1]).format('YYYY-MM-DD');
		delete data.paramTimeType;
		delete data.paramTime;
	}
	return data;
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getTableList"
const getTableList = async (params: any) => {
	const res = await fetchOrderBuy();
	if (res.code == 200) {
		orderBuyList.value = res.data;
	}
	const data = handleParams(params);
	return fetchOrderList(data);
};

const searchArr = [
	{
		label: '订单编号',
		value: 'orderNo',
	},
	{
		label: '交易号',
		value: 'tradeNo',
	},
	{
		label: 'SAP订单号',
		value: 'sapOrderNo',
	},
	{
		label: '用户ID',
		value: 'userId',
	},
	{
		label: '用户昵称',
		value: 'nickName',
	},
	{
		label: '收货人姓名',
		value: 'consigneeName',
	},
	{
		label: '收货人手机号',
		value: 'consigneePhone',
	},
	{
		label: '商品ID',
		value: 'productId',
	},
	{
		label: '商品名称',
		value: 'productName',
	},
	{
		label: '物料编码',
		value: 'materialCode',
	},
];
const timeSearchArr = [
	{
		label: '创建时间',
		value: 'create',
	},
	{
		label: '支付时间',
		value: 'pay',
	},
	{
		label: '发货时间',
		value: 'send',
	},
	{
		label: '完成时间',
		value: 'finish',
	},
];

// 表格配置项
const columns: ColumnProps<any>[] = [
	{
		prop: 'paramValue',
		label: '订单搜索',
		isShow: false,
		search: {
			span: 2,
			render: (scope: any) => {
				const slot = {
					prepend: () => (
						<el-select
							v-model={scope.searchParam.paramCode}
							placeholder="Select"
							style="width: 100px"
							onChange={(value) => (scope.searchParam.paramCode = value)}
						>
							{searchArr.map((item) => (
								<el-option key={item.value} label={item.label} value={item.value} />
							))}
						</el-select>
					),
				};
				return <el-input v-model={scope.modelValue} v-slots={slot} placeholder={getPlaceholder.value} maxlength={50}></el-input>;
			},
		},
	},
	{
		prop: 'paramTime',
		label: '订单时间',
		isShow: false,
		search: {
			span: 2,
			render: (scope: any) => {
				return (
					<div class="flex-center">
						<el-select
							v-model={scope.searchParam.paramTimeType}
							placeholder="Select"
							style="width: 100px"
							class="mini-gray-select flex-shrink"
							onChange={(value) => (scope.searchParam.paramTimeType = value)}
						>
							{timeSearchArr.map((item) => (
								<el-option key={item.value} label={item.label} value={item.value} />
							))}
						</el-select>
						<el-date-picker
							v-model={scope.searchParam.paramTime}
							type="datetimerange"
							start-placeholder="开始时间"
							end-placeholder="结束时间"
							format="YYYY-MM-DD HH:mm:ss"
							date-format="YYYY-MM-DD"
							time-format="HH:mm:ss"
						/>
					</div>
				);
			},
		},
	},

	{
		prop: 'appType',
		label: '订单来源',
		minWidth: 120,
		isShow: false,
		search: { el: 'select', props: { placeholder: '选择订单来源', clearable: true, filterable: true } },
		enum: [
			{
				label: '支付宝',
				value: 0,
			},
			{
				label: '微信',
				value: 1,
			},
		],
	},
	{
		prop: 'consigneeRemark',
		label: '买家备注',
		minWidth: 120,
		isShow: false,
		search: { el: 'select', props: { placeholder: '选择买家备注', clearable: true, filterable: true } },
		enum: [
			{
				label: '有备注',
				value: 1,
			},
			{
				label: '无备注',
				value: 0,
			},
		],
	},
	{
		prop: 'sellerRemark',
		label: '商家备注',
		minWidth: 120,
		isShow: false,
		search: { el: 'select', props: { placeholder: '选择商家备注', clearable: true, filterable: true } },
		enum: [
			{
				label: '有备注',
				value: 1,
			},
			{
				label: '无备注',
				value: 0,
			},
		],
	},
	{
		prop: 'userType',
		label: '用户类型',
		minWidth: 120,
		isShow: false,
		search: { el: 'select', props: { placeholder: '选择用户类型', clearable: true, filterable: true } },
		enum: [
			{
				label: '个人',
				value: 0,
			},
			{
				label: '经销商',
				value: 1,
			},
		],
	},
	{
		prop: 'orderNo',
		label: '订单编号',
		minWidth: 240,
		render: (scope) => {
			return (
				<el-link type="primary" underline={false} onClick={() => router.push(`/order/query/detail/${scope.row.id}`)}>
					{scope.row.orderNo}
				</el-link>
			);
		},
	},
	{
		prop: 'createTime',
		label: '创建时间',
		minWidth: 160,
	},
	{
		prop: 'requestTime',
		label: '下单商品',
		minWidth: 300,
		showOverflowTooltip: false,
		render: (scope) => {
			const unit = ['盒', '瓶', '件'];
			const slot = {
				content: () =>
					scope.row.products?.map((v: any) => (
						<div class="flex-center mb5">
							<el-image src={v.productImage} style="width: 50px; height: 50px;flex-shrink:0; margin-right: 10px;" fit="cover"></el-image>
							{v.materialCode}｜{v.productName}｜{v.skuName}:x{v.productAmount}
							{unit[v.materialUnit] || ''}
						</div>
					)),
			};
			return (
				<el-tooltip v-slots={slot}>
					{scope.row.products?.map((v: any) => (
						<div class="flex-center mb5">
							<el-image src={v.productImage} style="width: 50px; height: 50px;flex-shrink:0; margin-right: 10px;" fit="cover"></el-image>
							<div class="ellipsis2 text-left">
								{v.materialCode}｜{v.productName}｜{v.skuName}:x{v.productAmount}
								{unit[v.materialUnit] || ''}
							</div>
							<br />
						</div>
					))}
				</el-tooltip>
			);
		},
	},
	{
		prop: 'companyName',
		label: '收货人信息',
		minWidth: 240,
		align: 'left',
		render: (scope) => {
			return (
				<div>
					<div class="flex-center">
						<div class="text-primary mr5">{scope.row.consignee.nickName}</div>
						<el-tag type={scope.row.consignee.userType ? 'primary' : 'success'}>{constant.USERTYPE[scope.row.consignee.userType]}</el-tag>
					</div>
					<div class="flex-center">
						<div>{scope.row.consignee.consigneeName}</div>—<div>{scope.row.consignee.consigneePhone}</div>
					</div>
				</div>
			);
		},
	},
	{
		prop: 'orderStatus',
		label: '订单状态',
		minWidth: 120,
		enum: [
			{
				label: '待付款',
				value: 0,
			},
			{
				label: '待发货',
				value: 1,
			},
			{
				label: '已发货',
				value: 2,
			},
			{
				label: '已完成',
				value: 3,
			},
			{
				label: '已关闭',
				value: 4,
			},
		],
	},
	{
		prop: 'payAmount',
		label: '实收金额(元)',
		minWidth: 150,
		render: (scope) => {
			return fenToYuan(scope.row.payAmount);
		},
	},
	{
		prop: 'orderType',
		label: '订单类型',
		minWidth: 140,
		enum: [
			{
				label: 'B2C实物订单',
				value: 0,
			},
			{
				label: 'B2C酒藏订单',
				value: 1,
			},
			{
				label: 'C2C酒藏订单',
				value: 2,
			},
			{
				label: '酒藏提货订单',
				value: 3,
			},
			{
				label: '代管费订单',
				value: 4,
			},
		],
	},
	{
		prop: 'consigneeRemark',
		label: '买家备注',
		minWidth: 200,
		render: (scope) => {
			return scope.row.consigneeRemark || '--';
		},
	},
	{
		prop: 'sellerRemark',
		label: '商家备注',
		minWidth: 200,
		render: (scope) => {
			return scope.row.sellerRemark || '--';
		},
	},
	{ prop: 'operation', label: '操作', fixed: 'right', width: 160, align: 'left' },
];

const getPlaceholder = computed(() => {
	const target = searchArr.find((item) => {
		return item.value == proTable.value?.searchParam.paramCode;
	});
	return target ? `输入${target?.label}搜索` : '';
});

const remarkVisible = ref(false);
const remarkRow = ref();

// 保存并导出
const onExport = () => {
	ElMessageBox.confirm('确认导出数据?', '温馨提示', { type: 'warning' }).then(() =>
		useDownload(fetchOrderExport, '订单列表', handleParams(proTable.value?.searchParam))
	);
};

// 推送履约
const onPush = (row: any) => {
	ElMessageBox.confirm('确认推送履约？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
		beforeClose: async (action, instance, done) => {
			if (action === 'confirm') {
				instance.confirmButtonLoading = true;
				// 在此处调用方法，方法完成后需使用 done() 关闭弹框
				const res = await fetchOrderPush({ id: row.id });
				if (res.code === 200) {
					ElMessage.success('推送履约成功');
					row.pushStatus = 1;
					done();
				}
			} else {
				done();
			}
		},
	});
};

const onRemark = (row: any) => {
	remarkVisible.value = true;
	remarkRow.value = row;
};

const closeRemark = (success: boolean) => {
	remarkVisible.value = false;
	if (success) {
		proTable.value?.getTableList();
	}
};
</script>

<style lang="scss">
.demnd-width-scroll {
	display: flex;
	width: 100%;
	overflow-x: auto;
	scrollbar-width: none;
	scrollbar-color: transparent transparent;
	margin-bottom: 20px;
	&::-webkit-scrollbar {
		display: none;
	}
	.material {
		border: 1px solid var(--el-border-color);
		border-radius: 8px;
		padding: 8px 10px;
		width: 200px;
		color: var(--el-text-color-regular);
		line-height: 26px;
		flex-shrink: 0;
		margin-right: 10px;
	}
}
</style>
